package com.aliyun.heiyu.powermaster.server.util;

import com.aliyun.heiyu.common.util.LogUtils;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.SM4Util;
import com.aliyun.heiyu.powermaster.server.dao.entity.IscMail;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.List;

/**
 * 
 * 邮件发送
 * 
 * @author WANGHT ON 2020年5月23日 16:38:57
 *
 */
public class MailSendUtil implements Serializable {

	private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(MailSendUtil.class);

	public static boolean send(IscMail mail) {
		SimpleEmail email = new SimpleEmail();
        logger.info("==================MailSendUtil-IscMail:{}==================", mail);
		try {
			if (StringUtils.isBlank(mail.getHost())) {
			    //邮箱服务地址为空
                logger.info("邮箱服务地址为空【{}】", LogUtils.vaildlog(mail.getHost()));
				return false;
			}
			if ((mail.getReceiver() == null) || (mail.getReceiver().size() == 0)) {
				return false;
			}
			email.setHostName(mail.getHost());
			email.setSmtpPort(Integer.parseInt(mail.getPort()));
			email.setSSLCheckServerIdentity(Boolean.parseBoolean(mail.getUseSSL()));
			email.setSSLOnConnect(Boolean.parseBoolean(mail.getUseSSL()));

            email.setAuthentication(mail.getUsername(), SM4Util.decrypt_CBC(PropertiesUtil.getValue("serverIp.properties", "g_pd_sender")));
			email.setFrom(mail.getUsername());
			// 发送到
			for (String rec : mail.getReceiver()) {
				if (StringUtils.isNotBlank(rec)) {
					email.addTo(rec);
				}
			}
			email.setSubject(mail.getSubject());
			email.setCharset("gb2312");
			email.setMsg(mail.getMessage());
			email.setContent(mail.getMessage(),"text/plain;charset=gb2312");
			email.send();
			if (logger.isInfoEnabled()) {
                logger.info("{}发送邮件到 {}", LogUtils.vaildlog(mail.getSender()), mail.getReceiver());
			}
			return true;
		} catch (EmailException e) {
            logger.error(String.format("%s邮件发送到%s失败", new Object[] { LogUtils.vaildlog(mail.getSender()), mail.getReceiver() }), e);
		}
		return false;
	}

	public static boolean send(IscMail mail, List<String> receivers, String subject, String msg) {
		mail.setReceiver(receivers);
		mail.setSubject(subject);
		mail.setMessage(msg);
		return send(mail);
	}
}
